import React, { PureComponent } from 'react';
import moment from 'moment';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Row, Col, Input, Select } from 'antd';
import { TableC, SecondHeaderC, ModalC, SingleDateC, InputC, SelectC, InputNumberC } from '../../../comps';

const FormItem = Form.Item;
import { connect } from 'dva';
import { formSelectData } from '../../../utils/utils';

@Form.create()
@connect(({ accountNumberM, globalM }) => ({ accountNumberM, globalM }))
export default class ChangeModalC extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      flag: '0',
      headBankList: [], //总行下拉列表
      selProductList: [], //产品下拉选择框列表
      accountTypeList: [], //存款类型下拉选择框列表
      initialValue: undefined, // 默认无初始化值
      historyColumns: [], // 历史记录表格
      historyDataSource: [], //历史记录数据
      branchtips: '', //分行提示文本
    };
  }
  componentDidMount() {
    // 编辑状态下拿到flag的值
    this.getFlag();
    const {
      globalM: {
        dataDictionary: { CKLX = [] },
      },
    } = this.props;
    // 获取存款类型下拉列表
    this.setState({
      accountTypeList: formSelectData(CKLX),
    });
    // 获取产品下拉列表
    this.getProduct();
    // 根据id获取历史记录
    this.getHistoryById();
    this.getHeadBankList();
  }
  //模糊查询总行列表
  getHeadBankList = (e) => {
    if (!e) {
      this.props.dispatch({
        type: 'accountNumberM/getbankAccountList',
        payload: {
          currentPage: 1,
          numInPage: 20,
        },
        callback: (type, data) => {
          if (type == 'success') {
            this.setState({
              headBankList: data,
            });
          }
        },
      });
    } else {
      this.timer ? clearTimeout(this.timer) : '';
      this.timer = setTimeout(() => {
        this.props.dispatch({
          type: 'accountNumberM/getbankAccountList',
          payload: {
            currentPage: 1,
            numInPage: 20,
            blankName: e,
          },
          callback: (type, data) => {
            if (type == 'success') {
              this.setState({
                headBankList: data,
              });
            } else {
              this.setState({
                headBankList: [],
              });
            }
          },
        });
      }, 500);
    }
  };
  getFlag = () => {
    if (this.props.isEdit) {
      this.setState({
        flag: this.props.editObj.accountType == '00' ? '1' : '0',
      });
    }
  };
  // 根据id获取历史记录
  getHistoryById = () => {
    this.props.dispatch({
      type: 'accountNumberM/getHistoryById',
      payload: { id: this.props.editObj.id },
      callback: (type, data) => {
        if (type == 'success') {
          this.setState({
            historyColumns: data.columns,
            historyDataSource: data.dataSource,
          });
        }
      },
    });
  };
  // 获取产品下拉列表
  getProduct = () => {
    this.props.dispatch({
      type: 'accountNumberM/getProductList',
      payload: {},
      callback: (type, data) => {
        if (type == 'success') {
          // 1.赋值
          this.setState({
            selProductList: data,
          });
        }
      },
    });
  };
  // 修改visible
  changeVisible = (msg) => {
    this.props.changeVisible(msg);
  };

  //根据存款类型判断是否显示最后两个输入框
  changeAccountType = (e) => {
    if (e && e == '00') {
      this.setState({
        flag: '1',
      });
    } else {
      this.setState({
        flag: '0',
      });
    }
  };
  // 存款分行鼠标悬停有提示文本
  branchTips = (e) => {
    this.setState({ branchtips: e.target.value });
  };
  // 新增/编辑 存款账号模态框内容
  addForm = () => {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6, offset: 0 },
      wrapperCol: { span: 18, offset: 0 },
    };
    return (
      <div>
        <Form>
          <Row>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <FormItem label='产品' {...formItemLayout}>
                {getFieldDecorator('portfolioCode', {
                  rules: [{ required: true, message: '请选择产品' }],
                  initialValue: this.props.isEdit ? this.props.editObj.rootPortfolioCode : '',
                })(
                  <Select showSearch disabled={this.props.isEdit}>
                    {this.state.selProductList &&
                      this.state.selProductList.map((item, index) => {
                        return (
                          <Select.Option title={item.portfolioCode + ' - ' + item.portfolioName} value={item.portfolioCode + ' - ' + item.portfolioName} key={index}>
                            {item.portfolioCode + ' - ' + item.portfolioName}
                          </Select.Option>
                        );
                      })}
                  </Select>,
                )}
              </FormItem>
            </Col>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <SelectC
                title='存款总行'
                form={this.props.form}
                formItemLayout={formItemLayout}
                allowClear={true}
                rules={[{ required: true, message: '请选择存款总行' }]}
                initialValue={this.props.isEdit ? this.props.editObj.bankName : ''}
                disabled={this.props.isEdit}
                dataIndex='bankName'
                dataSource={this.state.headBankList}
                onSearch={(e) => this.getHeadBankList(e)}
                filterOption={false}
              />
            </Col>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <FormItem label='存款分行' {...formItemLayout}>
                {getFieldDecorator('branchBankName', {
                  rules: [{ required: true, message: '请输入存款分行' }],
                  initialValue: this.props.isEdit ? this.props.editObj.branchBankName : '',
                })(<Input disabled={this.props.isEdit} onMouseOver={(e) => this.branchTips(e)} title={this.state.branchtips} />)}
              </FormItem>
            </Col>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <SelectC
                positionBody={true}
                title='存款类型'
                dataIndex='accountType'
                disabled={this.props.isEdit}
                dataSource={this.state.accountTypeList}
                onChange={(e) => this.changeAccountType(e)}
                form={this.props.form}
                rules={[{ required: true, message: '请选择存款类型' }]}
                initialValue={this.props.isEdit ? this.props.editObj.accountType : ''}
                placeholder='请选择'
                formItemLayout={formItemLayout}
              />
            </Col>
          </Row>
          <Row>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <InputC
                form={this.props.form}
                title='账户'
                dataIndex='account'
                initialValue={this.props.isEdit ? this.props.editObj.account : ''}
                formItemLayout={formItemLayout}
                rules={[{ required: true, message: '请输入账户!' }]}
              />
            </Col>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <InputC
                form={this.props.form}
                title='账户名称'
                dataIndex='accountName'
                initialValue={this.props.isEdit ? this.props.editObj.accountName : ''}
                formItemLayout={formItemLayout}
                rules={[{ required: true, message: '请输入账户名称!' }]}
              />
            </Col>
            <Col span={24} style={{ marginBottom: '10px' }}>
              <InputC
                form={this.props.form}
                title='大额支付号'
                dataIndex='paymentNo'
                initialValue={this.props.isEdit ? this.props.editObj.paymentNo : null}
                formItemLayout={formItemLayout}
              />
            </Col>
            {this.state.flag == '1' && (
              <Col span={24} style={{ marginBottom: '10px' }}>
                <InputNumberC
                  dataIndex='rate'
                  title={'活期利率'}
                  unit={'%'}
                  min={0}
                  precision={2}
                  splitStyle={true}
                  rules={[{ required: true, message: '请输入活期利率' }]}
                  form={this.props.form}
                  formItemLayout={formItemLayout}
                  initialValue={this.props.isEdit ? parseFloat((this.props.editObj.rate * 100).toFixed(2)) : ''}
                />
              </Col>
            )}
          </Row>
          {this.state.flag == '1' && (
            <Row>
              <Col span={24} style={{ marginBottom: '10px' }}>
                <SingleDateC
                  form={this.props.form}
                  title='开始时间'
                  rules={[{ required: true, message: '请输入开始时间' }]}
                  dataIndex='startDate'
                  initialValue={this.props.isEdit ? moment(this.props.editObj.startDate) : null}
                  formItemLayout={formItemLayout}
                />
              </Col>
            </Row>
          )}
        </Form>
      </div>
    );
  };
  // 新增账号确认
  addanOK = () => {
    const {
      form: { validateFields, resetFields },
    } = this.props;
    const { dispatch } = this.props;

    validateFields(['portfolioCode', 'bankName', 'branchBankName', 'accountType', 'account', 'accountName', , 'rate', 'startDate', 'paymentNo'], (err, fieldsValue) => {
      if (err) return;
      let tempProduct = fieldsValue.portfolioCode.split(' - ');
      let tempHeadOffice = fieldsValue.bankName.split(' ');
      const value = {
        id: this.props.isEdit ? this.props.editObj.id : undefined,
        productCode: this.props.isEdit ? this.props.editObj.rootPortfolioCode.split(' ')[0] : tempProduct[0], //产品代码
        productName: this.props.isEdit ? this.props.editObj.rootPortfolioName : tempProduct[1], //产品名称
        headOfficeName: this.props.isEdit ? this.props.editObj.bankName : tempHeadOffice[1], // 总行名称
        headOfficeNo: this.props.isEdit ? this.props.editObj.bankNo : tempHeadOffice[0], //总行No
        branch: fieldsValue.branchBankName, // 分行名称
        accountType: fieldsValue.accountType, //存款类型
        account: fieldsValue.account, //账户
        accountName: fieldsValue.accountName, //账户名
        callRate: this.state.flag ? parseFloat(fieldsValue.rate / 100).toFixed(4) : undefined, //活期利率
        startDate: this.state.flag ? moment(fieldsValue?.startDate).format('YYYY-MM-DD') : null, //开始时间
        paymentNo: fieldsValue.paymentNo, //大额支付号
      };
      if (this.props.isEdit) {
        // 编辑状态下
        dispatch({
          type: 'accountNumberM/editAccountById',
          payload: {
            ...value,
          },
          callback: (type) => {
            if (type == 'success') {
              resetFields();
              this.props.useGetTableData(true);
              this.changeVisible(false);
            }
          },
        });
      } else {
        // 新增状态下
        dispatch({
          type: 'accountNumberM/addAccount',
          payload: {
            ...value,
          },
          callback: (type) => {
            if (type == 'success') {
              this.setState({
                visible: false,
                flag: '0',
              });
              resetFields();
              this.props.useGetTableData(true);
              this.changeVisible(false);
            }
          },
        });
      }
    });
  };
  // 新增账号取消
  addanCancel = () => {
    const {
      form: { resetFields },
    } = this.props;
    this.changeVisible(false);
    this.setState({
      flag: '0',
    });
    resetFields();
  };
  render() {
    const { historyColumns, historyDataSource } = this.state;
    return (
      <ModalC title={this.props.isEdit ? '编辑' : '新建'} visible={this.props.visible} maskClosable={false} onOk={this.addanOK} onCancel={this.addanCancel} width={369}>
        <div>{this.addForm()}</div>
        {this.props.isEdit && this.state.flag == '1' ? (
          <div style={{ marginTop: 10 }}>
            <SecondHeaderC title='历史记录' />
            <TableC columns={historyColumns} loading={this.props.loading} dataSource={historyDataSource} rowKey='rowKey' hidePage={true} />
          </div>
        ) : null}
      </ModalC>
    );
  }
}
